<template>
  <div id="container">
    <a-row class="header">
      <a-col class="query">
        <a-range-picker
          show-time
          @change="changeDate"
          size="large"
          style="width: 400px"
          :placeholder="['开始日期', '结束日期']"
          v-model:value="rangeTime"
        />
      </a-col>
      <a-col class="query">
        <a-select
          v-model:value="tag"
          :options="tagOptions"
          mode="tags"
          size="large"
          placeholder="查询点位"
          style="width: 500px"
          :max-tag-text-length="maxLength"
        ></a-select>
      </a-col>
      <a-col class="query">
        <a-select
          v-model:value="value"
          label-in-value
          :size="size"
          style="width: 130px"
          :options="dtOptions"
          @change="dtChange"
          placeholder="选择时间"
          allow-clear
        ></a-select>
      </a-col>
      <a-col class="query1">
        <a-switch
          v-model:checked="checked"
          checked-children="开"
          un-checked-children="关"
          @change="fresh"
        />
      </a-col>
      <a-col class="query">
        <a-button type="primary" size="large" @click="renderChart" class="btn"
          >查询</a-button
        >
      </a-col>
    </a-row>
    <div id="chart"></div>
  </div>
</template>

<script setup>
import { queryPointList, queryHistory } from "../../utils/tdengineApi";
import { onMounted, onUnmounted, ref } from "vue";
import * as echarts from "echarts";
import "echarts/lib/component/grid";
import dayjs from "dayjs";
import { message } from "ant-design-vue";

const size = ref("large");
const value = ref();
const dtOptions = ref([
  {
    label: "最近 5 分钟",
    value: "5minute",
  },
  {
    label: "最近 30分钟",
    value: "30minute",
  },
  {
    label: "最近 1 小时",
    value: "1hour",
  },
  {
    label: "最近 3 小时",
    value: "3hour",
  },
  {
    label: "最近12 小时",
    value: "12hour",
  },
  {
    label: "最近 1 天",
    value: "1day",
  },
  {
    label: "最近 7  天",
    value: "7day",
  },
  {
    label: "最近 15 天",
    value: "15day",
  },
  {
    label: "最近 30 天",
    value: "30day",
  },
]);
const tag = ref([]);
const tagOptions = ref([]);
const checked = ref(false);
const maxLength = ref(10);
const rangeTime = ref();
let dateStart = "";
let dateEnd = "";
let timer = undefined;
let chart = undefined;
let chartOption = undefined;
let lastCount = 0;

onMounted(async () => {
  setTimeout(() => {
    handleSearch(value.value);
    chart = echarts.init(document.getElementById("chart"));
    chartOption = {
      legend: {
        data: [],
      },
      toolbox: {
        right: 10,
        feature: {
          dataZoom: {
            yAxisIndex: "none",
          },
          restore: {},
          saveAsImage: {},
          dataView: {},
        },
      },
      tooltip: {
        trigger: "axis",
      },
      dataZoom: [
        {
          start: 0,
          end: 100,
        },
        {
          type: "inside",
        },
      ],
      xAxis: [],
      yAxis: {
        type: "value",
      },
      series: [],
    };
  }, 100);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
  dateStart = "";
  dateEnd = "";
  chart = undefined;
  timer = undefined;
  chartOption = undefined;
});

window.addEventListener("resize", () => {
  if (chart) {
    setTimeout(() => {
      chart.resize();
    }, 100);
  }
});

const changeDate = (value, dateString) => {
  dateStart = new Date(dateString[0]).getTime();
  dateEnd = new Date(dateString[1]).getTime();
};

const handleSearch = (val) => {
  queryPointList().then((m) => {
    m.map((v) => {
      tagOptions.value.push({
        value: v.tagname,
      });
    });
  });
};

const renderChart = async () => {
  if (tag.value && tag.value.length > 0 && dateStart && dateEnd) {
    chartOption.series = [];
    chartOption.xAxis = [];
    for (let index = 0; index < tag.value.length; index++) {
      const point = tag.value[index];
      let { data } = await queryHistory(point, dateStart, dateEnd);
      if (data.length > 0) {
        let xData = data.map((element) => {
          return element.ts;
        });
        if (xData.length > 0) {
          chartOption.xAxis.push({
            type: "category",
            data: xData,
          });
        }

        chartOption.legend.data = tag.value;

        let yData = data.map((element) => {
          return Number(element.value);
        });

        chartOption.series.push({
          name: String(point),
          data: yData,
          type: "line",
        });
        if (index == tag.value.length - 1) {
          if (lastCount !== tag.value.length) {
            chart.clear();
          }
          lastCount = tag.value.length;
          setTimeout(() => {
            chart.setOption(chartOption);
          }, 100);
        }
      } else {
        message.warn("数据为空");
      }
    }
  }
};

const fresh = async () => {
  if (checked.value == true) {
    if (value.value) {
      switch (value.value.value) {
        case "5minute":
          cycle(-5, "m");
          break;
        case "30minute":
          cycle(-30, "m");
          break;
        case "1hour":
          cycle(-1, "h");
          break;
        case "3hour":
          cycle(-3, "h");
          break;
        case "12hour":
          cycle(-12, "h");
          break;
        case "1day":
          cycle(-1, "d");
          break;
        case "7day":
          cycle(-7, "d");
          break;
        case "15day":
          cycle(-15, "d");
          break;
        case "30day":
          cycle(-30, "d");
          break;
        default:
          checked.value = false;
          message.warn("不能查询" + value.value.value);
          break;
      }
    } else {
      value.value = {
        label: "最近 5 分钟",
        value: "5minute",
      };
      cycle(-5, "m");
    }
    setTimeout(() => {
      message.success("自动刷新已开启");
    }, 1000);
  } else {
    if (timer) {
      clearInterval(timer);
    }
    setTimeout(() => {
      message.success("自动刷新已关闭");
    }, 1000);
  }
};

const cycle = (time, datetype) => {
  if (timer) {
    clearInterval(timer);
  }
  timer = setInterval(async () => {
    changeDateTime(time, datetype);
    await renderChart();
  }, 1000);
};

const dtChange = () => {
  switch (value.value.value) {
    case "5minute":
      changeDateTime(-5, "m");
      break;
    case "30minute":
      changeDateTime(-30, "m");
      break;
    case "1hour":
      changeDateTime(-1, "h");
      break;
    case "3hour":
      changeDateTime(-3, "h");
      break;
    case "12hour":
      changeDateTime(-12, "h");
      break;
    case "1day":
      changeDateTime(-1, "d");
      break;
    case "7day":
      changeDateTime(-7, "d");
      break;
    case "15day":
      changeDateTime(-15, "d");
      break;
    case "30day":
      changeDateTime(-30, "d");
      break;
  }
  fresh();
};

const changeDateTime = (time, datetype) => {
  rangeTime.value = [dayjs(new Date()).add(time, datetype), dayjs(new Date())];
  dateStart = dayjs(new Date()).add(time, datetype).toDate().getTime();
  dateEnd = dayjs(new Date()).toDate().getTime();
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
  background: linear-gradient(to top right, #c6e6e8, #baccd9, #f2e7e5);
  overflow: hidden;
}
.header {
  height: 100px;
  background: #fff;
  box-shadow: 2px 2px 2px 1px rgba(230, 210, 213, 0.5);
  overflow-y: auto;
}
.query {
  margin-top: 25px;
  margin-left: 20px;
}
.query1 {
  margin-top: 33px;
  margin-left: 20px;
}
#chart {
  width: 100%;
  height: calc(100% - 100px);
  /* overflow-y: scroll; */
}
.btn {
  border-radius: 5px;
}
</style>
